package seismosurfer.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import seismosurfer.data.QuakeData;
import seismosurfer.util.TimeUtil;

/**
 * This servlet sends an XML document 
 * with the top events to the web client.
 *
 */
public class TopEventsServlet extends BaseServlet {
    
    private static final long serialVersionUID = 2217399585468646062L;

    public TopEventsServlet() {
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/xml");
        noCache(response);

        List topEvents = (List) request.getSession().getAttribute("top");
        String xml = transformQuakesInXML(topEvents);

        response.getWriter().println(xml);

    }
    
    /**
     * Creates an XML document from a list of 
     * earthquake data.
     * <b>Change implementation!</b>
     * 
     * @param result the List with the earthquake data
     * @return a String that contains the XML document      
     */
    protected String transformQuakesInXML(List result) {

        StringBuffer xml = new StringBuffer();
        xml.append("<quakes>\n");

        int size = result.size();
        for (int i = 0; i < size; i++) {
            xml.append("<quake\t");
            QuakeData quake = (QuakeData) result.get(i);
            xml.append("time=\"" + TimeUtil.toText(quake.getDateTime()) + " GMT"
                    + "\"\t");
            xml.append("lat=\"" + quake.getLatitude() + "\"\t");
            xml.append("lng=\"" + quake.getLongitude() + "\"\t");
            xml.append("depth=\"" + quake.getDepth() + "\"\t");
            xml.append("mag=\"" + quake.getMagnitude() + "\"\t");

            xml.append("/>\n");
        }

        xml.append("</quakes>");

        return xml.toString();

    }

}